package com.rongdu.service;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rongdu.api.points.CommonOrderResponse;
import com.rongdu.api.points.GatewayResponse;
import com.rongdu.api.points.HttpClientHelper;
import com.rongdu.api.points.SignatureUtil;
import com.rongdu.context.Global;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Random;
import java.util.TreeMap;

/**
 * 积分商城变动提示接口
 */
@Service
public class DTChainService {

    private final static Gson gson = new Gson();

    private final static Logger LOG = LoggerFactory.getLogger(DTChainService.class);

    private final static String METHOD_POST = "POST";

    private final static String METHOD_GET= "GET";

    /**
     * 应用Access_Key
     *
     * 开发环境： 3778e6cf3f414ce2
     * 提测环境： 7a1791d5e904e84a
     * 线上： 3d42a79c1ec2bb19
     */
    private String accessKey;

    /**
     * 应用Secret_Key
     *
     * 开发环境： a6976bbb06845fd94818bf5a421d58d0
     * 提测环境： 43135a2530ede771c04da4cc9a915aa7
     * 线上： 1427494a77d46391641e7b07952c255
     */
    private String secretKey;

    /**
     * 数链网关入口
     *
     * 开发环境： https://gateway.iep.dtchain.io
     * 提测环境： https://gateway.p.dtchain.io
     * 线上： https://gateway.gljf.dtchain.io
     */
    private String apiEndpoint;

    // 积分变更通知接口
    private final String apiChangeUserIntegral = "/v1/gouli/user/%d/integral";

    // 积分变更通知接口
    private final String apiChangeIntegralResult = "/v1/gouli/integral/trx/result";

    /**
     * 通知数链用户积分变动
     *
     * @param userId 用户ID
     * @param integral 变动的积分值（目前只支持增加积分）
     * @param orderNo 够力侧订单号（如果有）
     * @param memo 够力侧积分变动备注（如果有）
     * @return
     */
    public GatewayResponse<CommonOrderResponse> changeUserIntegral(Long userId, Long integral, String orderNo,
                                                                   String memo, String orderTime) {
        init(userId);
        TreeMap<String, Object> params = _buildParams();
        params.put("integral", integral);
        if (!StringUtils.isEmpty(orderNo)) {
            params.put("order_no", orderNo);
        }
        if (!StringUtils.isEmpty(memo)) {
            params.put("memo", memo);
        }
        if (!StringUtils.isEmpty(orderTime)) {
            params.put("order_time", orderTime);
        }
        try {
            String api = String.format(apiChangeUserIntegral, userId);
            params.put(SignatureUtil.HEADER_INVOKE_SIGNATURE, SignatureUtil.sign(SignatureUtil.makeSignPlainText(params,
                    METHOD_POST, api), secretKey));
            return gson.fromJson(HttpClientHelper.isHttpsRequst(apiEndpoint) ?
                            HttpClientHelper.doPostSSL(apiEndpoint + api, params)
                            : HttpClientHelper.doPost(apiEndpoint + api, params),
                    new TypeToken<GatewayResponse<CommonOrderResponse>>(){}.getType());
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
        return null;
    }

    /**
     * 通知数链用户积分变动
     *
     * @param ticketId 任务ID
     * @return
     */
    public GatewayResponse<CommonOrderResponse> changeIntegralResult(String ticketId) {
        init(null);
        TreeMap<String, Object> params = _buildParams();

        try {
            params.put("ticket_id", ticketId);
            String sign = SignatureUtil.sign(SignatureUtil.makeSignPlainText(params, METHOD_GET, apiChangeIntegralResult), secretKey);
            params.put(SignatureUtil.HEADER_INVOKE_SIGNATURE, sign);
            String url = apiEndpoint + apiChangeIntegralResult;

            return gson.fromJson(HttpClientHelper.isHttpsRequst(apiEndpoint) ? HttpClientHelper.doGetSSL(url, params)
                            : HttpClientHelper.doGet(url, params),
                    new TypeToken<GatewayResponse<CommonOrderResponse>>() {
                    }.getType());
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
        return null;
    }

    private TreeMap<String, Object> _buildParams() {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put(SignatureUtil.HEADER_INVOKE_ACCESS_KEY, accessKey);
        params.put(SignatureUtil.HEADER_INVOKE_NONCE, _nextLong(8));
        params.put(SignatureUtil.HEADER_INVOKE_TIMESTAMP, System.currentTimeMillis() / 1000);

        return params;
    }

    private static Random _getRandom() {
        return java.util.concurrent.ThreadLocalRandom.current();
    }

    private static long _nextLong(int length) {
        int min = new BigDecimal(Math.pow(10, length - 1)).intValue();
        int max = new BigDecimal(Math.pow(10, length)).intValue() - 1;
        return (long) (min + ((max - min) * _getRandom().nextDouble()));
    }

    /**
     * 暂时设定，部分账户走开发环境部分走提测环境
     *
     * @param userId 用户ID
     */
    private void init(Long userId) {
        accessKey = Global.getString("DTChain_accessKey");
        secretKey = Global.getString("DTChain_secretKey");
        apiEndpoint = Global.getString("DTChain_apiEndpoint");
    }
}
